package com.macro.mall.product.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.product.constant.Constants;
import com.macro.mall.product.dto.*;
import com.macro.mall.product.service.*;
import com.macro.mall.product.util.DozerUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class PmProductServiceImpl implements PmProductService {
    @Autowired
    private PmProductMapper pmProductMapper;
    @Autowired
    private PmProdPicMapper pmProdPicMapper;
    @Autowired
    private PmProdSkuInstMapper pmProdSkuInstMapper;
    @Autowired
    private PmProdPricePlanPrptyRelMapper pmProdPricePlanPrptyRelMapper;
    @Autowired
    private PmPrptyPackageMapper pmPrptyPackageMapper;
    @Autowired
    private PmProdChannelMapper pmProdChannelMapper;
    @Autowired
    private PmProdSpecStockTempMapper pmProdSpecStockTempMapper;
    @Autowired
    private PmProdStockTempMapper pmProdStockTempMapper;
    @Autowired
    private PmProdPrptyService pmProdPrptyService;
    @Autowired
    private PmProdStockSetMapper pmProdStockSetMapper;

    @Autowired
    private PmServerSpecMapper pmServerSpecMapper;

    @Autowired
    private PmProdPrptyMapper pmProdPrptyMapper;
    @Autowired
    private PmProdPrptyValMapper pmProdPrptyValMapper;
    @Autowired
    private PmProdSpecSkuService pmProdSpecSkuService;
    @Autowired
    private Mapper mapper;

    @Autowired
    private PmPrptyService pmPrptyService;
    @Autowired
    private PmProdServiceTypeMapper pmProdServiceTypeMapper;
    @Autowired
    private PmProdReleaseAreaMapper pmProdReleaseAreaMapper;
    @Autowired
    private CommonService commonService;

    @Autowired
    private PmProdSpecService prodSpecService;

    @Autowired
    private CnRegionInfoMapper cnRegionInfoMapper;

    @Autowired
    private PmProdSpecMapper pmProdSpecMapper;

    @Override
    public List<PmProdSpec> list(PmProdSpecDto param) {

        PmProdSpec record = new PmProdSpec();
        if(!StringUtils.isBlank(param.getSpecName())){
            record.setSpecName(param.getSpecName());
        }
        if(param.getServerSpecId()!=null){
            record.setServerSpecId(param.getServerSpecId());
        }
//        List<PmProdSpec> prodSpecList =pmProdSpecMapper.selectList(record);
////        return prodSpecList;
        return null;
    }
    @Override
    public List<PmProdSpec> listPage(int pageNum, int pageSize,PmProdSpecDto param) {
        PageHelper.startPage(pageNum, pageSize);
        List<PmProdSpec> prodSpecList = this.list(param);
        return prodSpecList;
    }

    @Override
    public int save(PmProductDto productDto){
        int count =0;
        if(productDto!=null){
            /**1.数据转换******************/
            PmProduct product= mapper.map(productDto,PmProduct.class);
            Date curDate = new Date();

            /**2.基础数据保存******************/
            if(product.getId()!=null && product.getId()>0){
               // prodSpec.setUpdateBy("xx");
                product.setUpdateTime(curDate);
                count= pmProductMapper.updateByPrimaryKey(product);
            }else{
               // prodSpec.setUpdateBy("xx");
                product.setUpdateTime(curDate);
              //   prodSpec.setCreateBy("xx");
                product.setCreateTime(curDate);
//                product.setStatus(Constants.STATUS_VALID);
                count= pmProductMapper.insert(product);

                if(StringUtils.isBlank(product.getProdCode())){
                    PmProduct productTemp = new PmProduct();
                    productTemp.setId(product.getId());
                    productTemp.setProdCode(product.getId().toString());
                    pmProductMapper.updateByPrimaryKeySelective(productTemp);
                    product.setProdCode(product.getId().toString());
                    productDto.setProdCode(product.getId().toString());
                }
            }
            productDto.setId(product.getId());
            productDto.setProdCode(product.getProdCode());

            /**3.属性保存******************/
//            savePic(productDto);
              savePrpry(productDto);
            /**4.Sku保存*******************/
            saveSkuStock(productDto);
            /**5.模板保存******************/
            saveStockTemp(productDto);
            /**6.渠道保存******************/
            saveProdChannel(productDto);
            /**7.服务方式保存******************/
            saveProdServiceType(productDto);
            /**8.渠道保存******************/
           //  saveProdReleaseArea(productDto);
        }
        return  count;
    }
    public List<PmProdPic> getPicList(PmProdPic picParam){
        PmProdPicExample example  = new PmProdPicExample();
        PmProdPicExample.Criteria criteria = example.createCriteria();
        if(picParam.getProdId()!=null){
            criteria.andProdIdEqualTo(picParam.getProdId());
        }
        example.setOrderByClause(" pic_type asc , pic_seq asc ");
        List<PmProdPic> picList =pmProdPicMapper.selectByExample(example);
        return picList;
    }
    public List<PmProdSkuInst> getProdSkuInstList(PmProdSkuInst prodSkuInst){
        PmProdSkuInstExample skuExample  = new PmProdSkuInstExample();
        PmProdSkuInstExample.Criteria skuCriteria = skuExample.createCriteria();
        skuCriteria.andProdIdEqualTo(prodSkuInst.getProdId());
        if(!StringUtils.isBlank(prodSkuInst.getCode())){
            skuCriteria.andCodeEqualTo(prodSkuInst.getCode());
        }
        skuExample.setOrderByClause(" seq asc ");
        List<PmProdSkuInst> prodSkuInstList =pmProdSkuInstMapper.selectByExample(skuExample);
        if(prodSkuInstList!=null && prodSkuInstList.size()>0){
            PmProdPricePlanPrptyRelExample relExample;
            PmProdPricePlanPrptyRelExample.Criteria relCriteria ;
            List<PmProdPricePlanPrptyRel> pmProdPricePlanPrptyRelList;
            for(PmProdSkuInst prodSkuInstInfo : prodSkuInstList){
                relExample  = new PmProdPricePlanPrptyRelExample();
                relCriteria = relExample.createCriteria();
                relCriteria.andSkuInstIdEqualTo(prodSkuInstInfo.getId());
                relExample.setOrderByClause(" seq asc ");
                pmProdPricePlanPrptyRelList =  pmProdPricePlanPrptyRelMapper.selectByExample(relExample);
                prodSkuInstInfo.setProdPricePlanPrptyRelList(pmProdPricePlanPrptyRelList);
            }
        }
        return prodSkuInstList;
    }
    public List<PmProdChannel> getProdChannelList(PmProdChannel pmProdChannel){
        PmProdChannelExample example  = new PmProdChannelExample();
        PmProdChannelExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProdChannel.getProdId());
        List<PmProdChannel> prodChannelList =pmProdChannelMapper.selectByExample(example);
        return prodChannelList;
    }
    public PmProdStockTemp getStockTemp(Long prodId){

        PmProdStockTempExample example  = new PmProdStockTempExample();
        PmProdStockTempExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(prodId);
        List<PmProdStockTemp> prodStockTempList =pmProdStockTempMapper.selectByExample(example);
        if(prodStockTempList!=null && prodStockTempList.size()>0){
            return prodStockTempList.get(0);
        }else{
            return null;
        }
    }
    public List<PmProdStockSet> getProdStockSet(Long productId){
        PmProdStockSetExample example  = new PmProdStockSetExample();
        PmProdStockSetExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(productId);
        List<PmProdStockSet> prodStockSetList =pmProdStockSetMapper.selectByExample(example);
        return prodStockSetList;
    }
    public List<PmProdServiceType> getProdServiceType(Long prodId){
        PmProdServiceTypeExample example  = new PmProdServiceTypeExample();
        PmProdServiceTypeExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(prodId);
        List<PmProdServiceType> prodServiceTypeList =pmProdServiceTypeMapper.selectByExample(example);
        return prodServiceTypeList;
    }
    public List<PmProdReleaseArea> getProdReleaseArea(Long prodId){
        PmProdReleaseAreaExample example  = new PmProdReleaseAreaExample();
        PmProdReleaseAreaExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(prodId);
        List<PmProdReleaseArea> prodReleaseAreaList =pmProdReleaseAreaMapper.selectByExample(example);
        return prodReleaseAreaList;
    }
    private void saveSkuStock(PmProductDto pmProductDto){
        //1 删除原有数据
        PmProdSkuInstExample skuInstExample = new PmProdSkuInstExample();
        PmProdSkuInstExample.Criteria skuInstCriteria = skuInstExample.createCriteria();
        skuInstCriteria.andProdIdEqualTo(pmProductDto.getId());
        skuInstCriteria.andStatusEqualTo(String.valueOf(Constants.STATUS_VALID));
        pmProdSkuInstMapper.deleteByExample(skuInstExample);

        PmProdPricePlanPrptyRelExample prptyRelExample = new PmProdPricePlanPrptyRelExample();
        PmProdPricePlanPrptyRelExample.Criteria prptyRelCriteria = prptyRelExample.createCriteria();
        prptyRelCriteria.andProdIdEqualTo(pmProductDto.getId());
        prptyRelCriteria.andStatusEqualTo(Constants.STATUS_VALID);
        pmProdPricePlanPrptyRelMapper.deleteByExample(prptyRelExample);

        PmProdStockSetExample stockSetExample = new PmProdStockSetExample();
        PmProdStockSetExample.Criteria stockSetCriteria = stockSetExample.createCriteria();
        stockSetCriteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdStockSetMapper.deleteByExample(stockSetExample);

        PmProdReleaseAreaExample relaeaseAreaExample = new PmProdReleaseAreaExample();
        PmProdReleaseAreaExample.Criteria relaeaseAreaCriteria = relaeaseAreaExample.createCriteria();
        relaeaseAreaCriteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdReleaseAreaMapper.deleteByExample(relaeaseAreaExample);

        //2.判断上门还是到店
        int serviceType = 0 ;
        if(pmProductDto.getProdServiceTypeList() !=null && pmProductDto.getProdServiceTypeList().size()>0){
            PmProdServiceTypeDto serviceTypeDto = pmProductDto.getProdServiceTypeList().get(0);
            serviceType=serviceTypeDto.getServiceType();
        }
        //3.构造数据并保存
        if(serviceType==Constants.PROD_SERVER_TYPE_STORE) {
            if (pmProductDto.getSkuInstSaveList() != null && pmProductDto.getSkuInstSaveList().size() > 0) {
                for (int i = 0; i < pmProductDto.getSkuInstSaveList().size(); i++) {
                    JSONObject skuInfoObj = pmProductDto.getSkuInstSaveList().getJSONObject(i);

                    String skuCode = skuInfoObj.getString("skuCode");
                    JSONArray stockArray = skuInfoObj.getJSONArray("stockArray");
                    PmProdSkuInst skuInst = this.saveSku(pmProductDto, skuCode, i);
                    if (skuInst != null) {
                        this.saveStockSet(pmProductDto, skuInst, stockArray);
                    }
                }
            }
        }else if(serviceType==Constants.PROD_SERVER_TYPE_DOOR){

            Map<String,PmProdSkuInst> skuSavedMap = new HashMap<>();
            Map<String,PmProdReleaseArea> areaSavedMap = new HashMap<>();
            if (pmProductDto.getSkuInstSaveList() != null && pmProductDto.getSkuInstSaveList().size() > 0) {
                for (int i = 0; i < pmProductDto.getSkuInstSaveList().size(); i++) {
                    JSONObject skuInfoObj = pmProductDto.getSkuInstSaveList().getJSONObject(i);
//                    {
//                        "releaseAreaId": "130000_130600",
//                            "prpty_2": "中级",
//                            "price": "200.0",
//                            "prpty_1": "90分钟",
//                            "stockTime": "09:00-11:30",
//                            "stock": 0,
//                            "mainId": "1,2;2,6|3,3",
//                            "prptyNameShow_1": "时长",
//                            "prptyNameShow_2": "级别",
//                            "skuCode": "3",
//                            "releaseAreaName": "河北省/保定市"
//                    }

                    String skuCode = skuInfoObj.getString("skuCode");
                    PmProdSkuInst skuInst =skuSavedMap.get(skuCode) ;
                    if(skuInst==null){
                        skuInst = this.saveSku(pmProductDto, skuCode, i);
                        skuSavedMap.put(skuCode,skuInst);
                    }

                    String releaseAreaId = skuInfoObj.getString("releaseAreaId");
                    PmProdReleaseArea releaseArea  =areaSavedMap.get(releaseAreaId);
                    if(releaseArea==null){
                        String releaseAreaName = skuInfoObj.getString("releaseAreaName");
                        releaseArea = this.saveReleaseArea(pmProductDto.getId(), releaseAreaId, releaseAreaName);
                        areaSavedMap.put(releaseAreaId,releaseArea);
                    }
                    this.saveStockSetByDoor(pmProductDto, skuInst,skuInfoObj, releaseArea.getId());

                }
            }
        }
    }
    private  PmProdSkuInst saveSku(PmProductDto pmProductDto,String skuCode,int seq){
        PmSpecSku querySpecSku = new PmSpecSku();
        querySpecSku.setStatus(String.valueOf(Constants.STATUS_VALID));
        querySpecSku.setProdSpecId(pmProductDto.getProdSpecId());
        querySpecSku.setCode(skuCode);
        List<PmSpecSku> specSkuList = pmProdSpecSkuService.getSpecSkuList(querySpecSku);
        PmSpecSku specSkuDB = null;
        if (specSkuList != null && specSkuList.size() > 0) {
            specSkuDB = specSkuList.get(0);
        }
        if (specSkuDB == null) {
            return null;
        }
        //pm_prod_sku_inst
        PmProdSkuInst skuInst = new PmProdSkuInst();
        skuInst.setProdId(pmProductDto.getId());
        skuInst.setCode(specSkuDB.getCode());
        skuInst.setPrice(specSkuDB.getPrice());
        skuInst.setName(specSkuDB.getName());
        skuInst.setStatus(String.valueOf(Constants.STATUS_VALID));
        skuInst.setSeq(seq);
        pmProdSkuInstMapper.insert(skuInst);

        //pm_prod_price_plan_prpty_rel
        if (specSkuDB.getSpecPricePlanPrptyRelList()!=null &&specSkuDB.getSpecPricePlanPrptyRelList().size()>0){
            PmProdPricePlanPrptyRel  prodPrptyRel ;
            for(PmSpecPricePlanPrptyRel specPrptyRelDB : specSkuDB.getSpecPricePlanPrptyRelList()){
                prodPrptyRel = mapper.map(specPrptyRelDB,PmProdPricePlanPrptyRel.class);
                prodPrptyRel.setId(null);
                prodPrptyRel.setProdId(pmProductDto.getId());
                prodPrptyRel.setSkuInstId(skuInst.getId());
                pmProdPricePlanPrptyRelMapper.insert(prodPrptyRel);
            }
        }
        return  skuInst;
    }
    private  PmProdReleaseArea saveReleaseArea(Long productId,String releaseAreaId,String  releaseAreaName){

        String[] releaseAreaIdArray = releaseAreaId.split("_");
        String[] releaseAreaNameArray = releaseAreaName.split("/");
        PmProdReleaseArea releaseArea = new PmProdReleaseArea();
        if(releaseAreaIdArray.length>0){
            releaseArea.setProdId(productId);
            releaseArea.setProvCode(releaseAreaIdArray[0]);
            releaseArea.setProvName(releaseAreaNameArray[0]);
            if(releaseAreaIdArray.length>1){
                releaseArea.setCityCode(releaseAreaIdArray[1]);
                releaseArea.setCityName(releaseAreaNameArray[1]);
            }
            if(releaseAreaIdArray.length>2){
                releaseArea.setCountyCode(releaseAreaIdArray[2]);
                releaseArea.setCountyName(releaseAreaNameArray[2]);
            }
            pmProdReleaseAreaMapper.insert(releaseArea);
        }
        return  releaseArea;
    }
    private void saveStockSet(PmProductDto pmProductDto,PmProdSkuInst skuInst,JSONArray stockArray){
        if(stockArray!=null && stockArray.size()>0){
            PmProdChannelDto prodChannel = pmProductDto.getProdChannelList().get(0);
            JSONObject stockObj ;
            PmProdStockSet pmProdStockSet;
            for(int i=0;i<stockArray.size();i++){
                stockObj=stockArray.getJSONObject(i);
                pmProdStockSet = new PmProdStockSet();
                pmProdStockSet.setChannelId(prodChannel.getChannelId());
                pmProdStockSet.setChannelName(prodChannel.getChannelName());
                pmProdStockSet.setDealershipId(prodChannel.getDealershipId());
                pmProdStockSet.setDealershipName(prodChannel.getDealershipName());
                pmProdStockSet.setProdId(pmProductDto.getId());
                pmProdStockSet.setProdCode(pmProductDto.getProdCode());
                pmProdStockSet.setSkuInstId(skuInst.getId());
                pmProdStockSet.setSkuCode(skuInst.getCode());
                pmProdStockSet.setSkuName(skuInst.getName());
                pmProdStockSet.setType(Constants.STOCK_TASK_TYPE_DAILY);
                pmProdStockSet.setStockTime(stockObj.getString("stockTime"));
                pmProdStockSet.setTotalStock(Float.parseFloat(stockObj.getString("stock")));
                pmProdStockSet.setProdSpecId(pmProductDto.getProdSpecId());
                pmProdStockSetMapper.insert(pmProdStockSet);
            }
        }
    }
    private void saveStockSetByDoor(PmProductDto pmProductDto,PmProdSkuInst skuInst,JSONObject skuInfoObj,Long releaseAreaId){
        PmProdChannelDto prodChannel = pmProductDto.getProdChannelList().get(0);
        PmProdStockSet pmProdStockSet;
        pmProdStockSet = new PmProdStockSet();
        pmProdStockSet.setChannelId(prodChannel.getChannelId());
        pmProdStockSet.setChannelName(prodChannel.getChannelName());
        pmProdStockSet.setDealershipId(prodChannel.getDealershipId());
        pmProdStockSet.setDealershipName(prodChannel.getDealershipName());
        pmProdStockSet.setProdId(pmProductDto.getId());
        pmProdStockSet.setProdCode(pmProductDto.getProdCode());
        pmProdStockSet.setSkuInstId(skuInst.getId());
        pmProdStockSet.setSkuCode(skuInst.getCode());
        pmProdStockSet.setSkuName(skuInst.getName());
        pmProdStockSet.setType(Constants.STOCK_TASK_TYPE_DAILY_DOOR);
        pmProdStockSet.setStockTime(skuInfoObj.getString("stockTime"));
        pmProdStockSet.setTotalStock(Float.parseFloat(skuInfoObj.getString("stock")));
        pmProdStockSet.setProdSpecId(pmProductDto.getProdSpecId());
        pmProdStockSet.setReleaseAreaId(releaseAreaId);
        pmProdStockSetMapper.insert(pmProdStockSet);
    }
    private void savePrpry(PmProductDto pmProductDto){
        //1 删除原有属性、属性值
        PmProdPrptyExample prodPrptyExample = new PmProdPrptyExample();
        PmProdPrptyExample.Criteria prodPrptyCriteria = prodPrptyExample.createCriteria();
        prodPrptyCriteria.andProdIdEqualTo(pmProductDto.getId());
        prodPrptyCriteria.andStatusEqualTo(Constants.STATUS_VALID);
        pmProdPrptyMapper.deleteByExample(prodPrptyExample);

        PmProdPrptyValExample prodPrptyValExample = new PmProdPrptyValExample();
        PmProdPrptyValExample.Criteria prodPrptyValCriteria = prodPrptyValExample.createCriteria();
        prodPrptyValCriteria.andProdIdEqualTo(pmProductDto.getId());
        prodPrptyValCriteria.andStatusEqualTo(Constants.STATUS_VALID);
        pmProdPrptyValMapper.deleteByExample(prodPrptyValExample);
        //2.销售属性
        JSONArray  salePrptyArray = this.getSalePrptyArray(pmProductDto);
        //3.自然屬性构造属性、属性值数据
        if(pmProductDto.getNaturePrptySaveList()!=null && pmProductDto.getNaturePrptySaveList().size()>0){
            JSONObject prptyJSON = null;
            for(int i=0;i< pmProductDto.getNaturePrptySaveList().size();i++){
                prptyJSON=pmProductDto.getNaturePrptySaveList().getJSONObject(i);
                salePrptyArray.add(prptyJSON);
            }
        }
        //4.属性保存
        this.saveProdPrptyByJson(pmProductDto.getId(),salePrptyArray);
    }
//    private void saveNaturePrpty(PmProductDto pmProductDto){
//        if(pmProductDto.getNaturePrptySaveList()!=null && pmProductDto.getSkuInstSaveList().size()>0){
//            PmProdPrpty  prodPrptyDB;
//            PmProdPrptyVal  prodPrptyValDB;
//            JSONObject prptyJSON = null;
//            String prptyCode;
//            String prptyValCodes;
//            String[] prptyValCodeArray;
//            for(int i=0;i< pmProductDto.getNaturePrptySaveList().size();i++){
//                prptyJSON=pmProductDto.getNaturePrptySaveList().getJSONObject(i);
//                prptyCode=prptyJSON.getString("prptyCode");
//                prptyValCodes=prptyJSON.getString("prptyValCode");
//                if(StringUtils.isBlank(prptyCode)||StringUtils.isBlank(prptyValCodes)){
//                    continue;
//                }
//                PmPrpty pmPrpty =pmPrptyService.getByCode(prptyCode);
//                if(pmPrpty ==null){
//                    continue;
//                }
//                prodPrptyDB = new PmProdPrpty();
//                prodPrptyDB.setProdId(pmProductDto.getId());
//                prodPrptyDB.setPrptyCode(pmPrpty.getPrptyCode());
//                prodPrptyDB.setPrptyType(pmPrpty.getPrptyType());
//                prodPrptyDB.setPrptyName(pmPrpty.getPrptyName());
//                prodPrptyDB.setPrptyNameShow(pmPrpty.getPrptyNameShow());
//                prodPrptyDB.setPrptyDesc(pmPrpty.getPrptyDesc());
//                prodPrptyDB.setCategory(pmPrpty.getCategory());
//                prodPrptyDB.setPrptySeq(i);
//                prodPrptyDB.setStatus(Constants.STATUS_VALID);
//                pmProdPrptyMapper.insert(prodPrptyDB);
//
//                //保存屬性值
//                prptyValCodeArray = prptyValCodes.split(",");
//                if(prptyValCodeArray!=null && prptyValCodeArray.length>0
//                        && pmPrpty.getPrptyValList()!=null && pmPrpty.getPrptyValList().size()>0){
//
//                    for(int val_i=0;val_i<prptyValCodeArray.length;val_i++){
//                        for(PmPrptyVal prptyVal : pmPrpty.getPrptyValList()){
//                            if(prptyVal.getPrptyValCode().equals(prptyValCodeArray[val_i].trim())){
//                                prodPrptyValDB = new PmProdPrptyVal();
//                                prodPrptyValDB.setProdId(pmProductDto.getId());
//                                prodPrptyValDB.setPrptyCode(prptyVal.getPrptyCode());
//                                prodPrptyValDB.setPrptyValCode(prptyVal.getPrptyValCode());
//                                prodPrptyValDB.setPrptyValue(prptyVal.getPrptyValue());
//                                prodPrptyValDB.setStatus(Constants.STATUS_VALID);
//                                prodPrptyValDB.setPrptySeq(val_i);
//                                prodPrptyValDB.setProdPrptyId(prodPrptyDB.getId());
//                                pmProdPrptyValMapper.insert(prodPrptyValDB);
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }
    private void saveProdPrptyByJson(Long prodId,JSONArray prptyArray ){
        if(prptyArray!=null && prptyArray.size()>0){
            PmProdPrpty  prodPrptyDB;
            PmProdPrptyVal  prodPrptyValDB;
            JSONObject prptyJSON = null;
            String prptyCode;
            String prptyValCodes;
            String[] prptyValCodeArray;
            for(int i=0;i< prptyArray.size();i++){
                prptyJSON=prptyArray.getJSONObject(i);
                prptyCode=prptyJSON.getString("prptyCode");
                prptyValCodes=prptyJSON.getString("prptyValCode");
                if(StringUtils.isBlank(prptyCode)||StringUtils.isBlank(prptyValCodes)){
                    continue;
                }
                PmPrpty pmPrpty =pmPrptyService.getByCode(prptyCode);
                if(pmPrpty ==null){
                    continue;
                }
                prodPrptyDB = new PmProdPrpty();
                prodPrptyDB.setProdId(prodId);
                prodPrptyDB.setPrptyCode(pmPrpty.getPrptyCode());
                prodPrptyDB.setPrptyType(pmPrpty.getPrptyType());
                prodPrptyDB.setPrptyName(pmPrpty.getPrptyName());
                prodPrptyDB.setPrptyNameShow(pmPrpty.getPrptyNameShow());
                prodPrptyDB.setPrptyDesc(pmPrpty.getPrptyDesc());
                prodPrptyDB.setCategory(pmPrpty.getCategory());
                prodPrptyDB.setPrptySeq(i);
                prodPrptyDB.setStatus(Constants.STATUS_VALID);
                pmProdPrptyMapper.insert(prodPrptyDB);

                //保存屬性值
                prptyValCodeArray = prptyValCodes.split(",");
                if(prptyValCodeArray!=null && prptyValCodeArray.length>0
                        && pmPrpty.getPrptyValList()!=null && pmPrpty.getPrptyValList().size()>0){

                    for(int val_i=0;val_i<prptyValCodeArray.length;val_i++){
                        for(PmPrptyVal prptyVal : pmPrpty.getPrptyValList()){
                            if(prptyVal.getPrptyValCode().equals(prptyValCodeArray[val_i].trim())){
                                prodPrptyValDB = new PmProdPrptyVal();
                                prodPrptyValDB.setProdId(prodId);
                                prodPrptyValDB.setPrptyCode(prptyVal.getPrptyCode());
                                prodPrptyValDB.setPrptyValCode(prptyVal.getPrptyValCode());
                                prodPrptyValDB.setPrptyValue(prptyVal.getPrptyValue());
                                prodPrptyValDB.setStatus(Constants.STATUS_VALID);
                                prodPrptyValDB.setPrptySeq(val_i);
                                prodPrptyValDB.setProdPrptyId(prodPrptyDB.getId());
                                pmProdPrptyValMapper.insert(prodPrptyValDB);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    private JSONArray getSalePrptyArray(PmProductDto pmProductDto){
        Map<String,String>  prptyMap = new HashMap<String,String>();
        Map<String,String> prptyValMap = new HashMap<>();
        if(pmProductDto.getSkuInstSaveList()!=null && pmProductDto.getSkuInstSaveList().size()>0){
            for(int i=0;i<pmProductDto.getSkuInstSaveList().size();i++){
                JSONObject skuInfoObj = pmProductDto.getSkuInstSaveList().getJSONObject(i);
                String skuCode=skuInfoObj.getString("skuCode");

                PmSpecSku querySpecSku = new PmSpecSku();
                querySpecSku.setStatus(String.valueOf(Constants.STATUS_VALID));
                querySpecSku.setProdSpecId(pmProductDto.getProdSpecId());
                querySpecSku.setCode(skuCode);
                List<PmSpecSku> specSkuList = pmProdSpecSkuService.getSpecSkuList(querySpecSku);
                PmSpecSku specSkuDB = null;
                if (specSkuList != null && specSkuList.size() > 0) {
                    specSkuDB = specSkuList.get(0);
                }
                if (specSkuDB == null) {
                    continue;
                }
                if(specSkuDB.getSpecPricePlanPrptyRelList()!=null && specSkuDB.getSpecPricePlanPrptyRelList().size()>0){
                    String prptyValCodes;
                    String prptyValCodesSave;
                    for(PmSpecPricePlanPrptyRel prptyRel: specSkuDB.getSpecPricePlanPrptyRelList()){
                        prptyValCodes =prptyMap.get(prptyRel.getPrptyCode());
                        prptyValCodesSave=prptyValMap.get(prptyRel.getPrptyCode()+"_"+prptyRel.getPrptyValCode());
                        if(StringUtils.isBlank(prptyValCodesSave)) {
                            if (StringUtils.isBlank(prptyValCodes)) {
                                prptyValCodes = prptyRel.getPrptyValCode();
                            } else {
                                prptyValCodes = prptyValCodes + "," + prptyRel.getPrptyValCode();
                            }
                            prptyMap.put(prptyRel.getPrptyCode(), prptyValCodes);
                            prptyValMap.put(prptyRel.getPrptyCode()+"_"+prptyRel.getPrptyValCode(),prptyRel.getPrptyValCode());
                        }
                    }

                }
            }
        }
        JSONArray salePrptyArray = new JSONArray();
        JSONObject salePrptyObj;
        if(prptyMap!=null){
            for(String key : prptyMap.keySet()){
                salePrptyObj = new JSONObject();
                salePrptyObj.put("prptyCode",key);
                salePrptyObj.put("prptyValCode",prptyMap.get(key));
                salePrptyArray.add(salePrptyObj);
            }
        }
        return salePrptyArray;
    }
    private void savePic(PmProductDto pmProductDto){
        //1 删除原有图片
        PmProdPicExample example  = new PmProdPicExample();
        PmProdPicExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdPicMapper.deleteByExample(example);
        //2 构造图片数据
        List<PmProdPic> picList= new  ArrayList<PmProdPic>();
        if(StringUtils.isBlank(pmProductDto.getMainPicId())){
            int seq=0;
            String[] picArray=pmProductDto.getMainPicId().split(";");
            PmProdPic pic ;
            for(String picId :picArray) {
                pic = new PmProdPic();
                pic.setProdId(pmProductDto.getId());
                pic.setPicType(Constants.PROD_SPEC_PIC_TYPE_MAIN);
                seq++;
                pic.setPicSeq(seq);
                pic.setPicId(picId);
                picList.add(pic);
            }
        }
        //3 保存图片
        if(picList!=null && picList.size()>0){
            for(PmProdPic pic : picList){
                pmProdPicMapper.insert(pic);
            }
        }
    }

    private void saveStockTemp(PmProductDto pmProductDto){
        //1 删除原有数据
        PmProdStockTempExample example  = new PmProdStockTempExample();
        PmProdStockTempExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdStockTempMapper.deleteByExample(example);
        //2 保存  直接复制商品规格数据
        PmProdSpecStockTempExample specStockTempExample = new PmProdSpecStockTempExample();
        PmProdSpecStockTempExample.Criteria specStockTempCriteria = specStockTempExample.createCriteria();
        specStockTempCriteria.andProdSpecIdEqualTo(pmProductDto.getProdSpecId());
        specStockTempCriteria.andTempStatusEqualTo(Constants.STATUS_VALID);
        List<PmProdSpecStockTemp> list = pmProdSpecStockTempMapper.selectByExample(specStockTempExample);
        if(list!=null && list.size()>0){
            PmProdSpecStockTemp specStockTempDB = list.get(0);
            PmProdStockTemp prodStockTemp = mapper.map(specStockTempDB,PmProdStockTemp.class);
            prodStockTemp.setId(null);
            prodStockTemp.setProdId(pmProductDto.getId());
            pmProdStockTempMapper.insert(prodStockTemp);
        }
    }
    private void saveProdChannel(PmProductDto pmProductDto){
        //1 删除原有数据
        PmProdChannelExample example  = new PmProdChannelExample();
        PmProdChannelExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdChannelMapper.deleteByExample(example);
        //2 保存
        if(pmProductDto.getProdChannelList()!=null && pmProductDto.getProdChannelList().size()>0){
            PmProdChannel  prodChannel;
            for(PmProdChannelDto prodChannelDto : pmProductDto.getProdChannelList()){
                prodChannel = mapper.map(prodChannelDto,PmProdChannel.class);
                prodChannel.setProdId(pmProductDto.getId());
                prodChannel.setProdCode(pmProductDto.getProdCode());
                prodChannel.setProdSpecId(pmProductDto.getProdSpecId());
                prodChannel.setStauts(Constants.STATUS_VALID);
                prodChannel.setId(null);
                pmProdChannelMapper.insert(prodChannel);
            }
        }
    }
    private void saveProdServiceType(PmProductDto pmProductDto){
        //1 删除原有数据
        PmProdServiceTypeExample example  = new PmProdServiceTypeExample();
        PmProdServiceTypeExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdServiceTypeMapper.deleteByExample(example);
        //2 保存
        if(pmProductDto.getProdServiceTypeList()!=null && pmProductDto.getProdServiceTypeList().size()>0){
            PmProdServiceType   prodServiceType;
            for(PmProdServiceTypeDto prodServiceTypeDto : pmProductDto.getProdServiceTypeList()){
                prodServiceType = mapper.map(prodServiceTypeDto,PmProdServiceType.class);
                prodServiceType.setProdId(pmProductDto.getId());
                pmProdServiceTypeMapper.insert(prodServiceType);
            }
        }
    }
    private void saveProdReleaseArea(PmProductDto pmProductDto){
        //1 删除原有数据
        PmProdReleaseAreaExample example  = new PmProdReleaseAreaExample();
        PmProdReleaseAreaExample.Criteria criteria = example.createCriteria();
        criteria.andProdIdEqualTo(pmProductDto.getId());
        pmProdReleaseAreaMapper.deleteByExample(example);
        //2 保存
        if(pmProductDto.getProdReleaseAreaList()!=null && pmProductDto.getProdReleaseAreaList().size()>0){
            PmProdReleaseArea   prodReleaseArea;
            for(PmProdReleaseAreaDto prodReleaseAreaDto : pmProductDto.getProdReleaseAreaList()){
                prodReleaseArea = mapper.map(prodReleaseAreaDto,PmProdReleaseArea.class);
                prodReleaseArea.setProdId(pmProductDto.getId());
                pmProdReleaseAreaMapper.insert(prodReleaseArea);
            }
        }
    }
    @Override
    public PmProduct getById(Long id){
        PmProduct pmProduct =pmProductMapper.selectByPrimaryKey(id);

        //图片信息
//        PmProdPic pic = new PmProdPic();
//        pic.setProdId(pmProduct.getId());
//        pmProduct.setPicList(getPicList(pic));

//        //品类包信息
//        PmPrptyPackage prptyPackage=pmPrptyPackageMapper.selectByPrimaryKey(pmProduct.getPrptyPackageId());
//        pmProduct.setPrprtyPackage(prptyPackage);

        //商品属性
        PmProdPrpty param = new PmProdPrpty();
        param.setProdId(pmProduct.getId());
        List<PmProdPrpty>  prodPrptyList = pmProdPrptyService.listProdPrpty(param);
        pmProduct.setProdPrptyList(prodPrptyList);

        //SKU信息
        PmProdSkuInst pmProdSkuInst = new PmProdSkuInst();
        pmProdSkuInst.setProdId(pmProduct.getId());
        pmProduct.setSkuInstList(getProdSkuInstList(pmProdSkuInst));

        //渠道信息
        PmProdChannel pmProdChannel = new PmProdChannel();
        pmProdChannel.setProdId(pmProduct.getId());
        pmProduct.setProdChannelList(getProdChannelList(pmProdChannel));

        //库存设置信息
        pmProduct.setProdStockSetList(getProdStockSet(pmProduct.getId()));

        //为前端展示，封装SKU 库存表头以及数据信息
        JSONArray labelArray = new JSONArray();
        JSONArray skuTableData = new JSONArray();
        this.buildSkuStoreShow(labelArray,skuTableData,pmProduct.getSkuInstList(),pmProduct.getProdStockSetList());
        pmProduct.setLabelArrayList(labelArray);
        pmProduct.setSkuTableDataList(skuTableData);

        //服务方式
        pmProduct.setProdServiceTypeList(getProdServiceType(pmProduct.getId()));
        //发布范围
        pmProduct.setProdReleaseAreaList(getProdReleaseArea(pmProduct.getId()));

        pmProduct.setProdStockTemp(getStockTemp(pmProduct.getId()));

        return pmProduct;
    }
    @Override
    public List<PmProductDto> converDataList(List<PmProduct> productList) {
//        if(productList!=null && productList.size()>0){
//            for(PmProduct pmProduct : productList){
//                converDataPic(pmProduct);
//            }
//        }
        List<PmProductDto> dtoList = DozerUtils.mapList(mapper, productList, PmProductDto.class);
        return dtoList;
    }
    @Override
    public PmProductDto converDataInfo(PmProduct pmProduct) {
        // converDataPic(pmProduct);
        PmProductDto productDto= mapper.map(pmProduct,PmProductDto.class);
//        converDataSkuStore(pmProduct);
       //  converDataPic(pmProduct);
        if(pmProduct.getLabelArrayList()!=null){
            productDto.setLabelArrayShow(pmProduct.getLabelArrayList());
        }
        if(pmProduct.getSkuTableDataList()!=null){
            productDto.setSkuTableDataShow(pmProduct.getSkuTableDataList());
        }
        return productDto;
    }

    @Override
    public PmProductViewDto converDataInfoView(PmProduct pmProduct) {
        PmProductViewDto productViewDto= mapper.map(pmProduct,PmProductViewDto.class);

        if(pmProduct!=null && pmProduct.getServerSpecId()!=null){
            PmServerSpec pmServerSpec  = pmServerSpecMapper.selectByPrimaryKey(pmProduct.getServerSpecId());
            if(pmServerSpec!=null ){
                productViewDto.setServerSpecName(pmServerSpec.getServerSpecName());
                productViewDto.setServerSpecId(pmServerSpec.getId());
            }
        }
        if(pmProduct.getProdChannelList()!=null && pmProduct.getProdChannelList().size()>0){
            PmProdChannel channel = pmProduct.getProdChannelList().get(0);
            productViewDto.setChannelName(channel.getChannelName());
            productViewDto.setDealershipName(channel.getDealershipName());
            productViewDto.setChannelId(channel.getChannelId());
            productViewDto.setDealershipId(channel.getDealershipId());
        }

        /**属性值封装*********************/
        List<Map<String,String>> prptyShowList = new ArrayList<Map<String,String>>();
        if(pmProduct!=null && pmProduct.getProdPrptyList().size()>0){
            String values;
            String prptyType;
            PmProdPrpty prpty;
            Map<String,String>  prptyShowMap;
            for(int i=0;i< pmProduct.getProdPrptyList().size();i++){
                values ="";
                prpty = pmProduct.getProdPrptyList().get(i);
                if(prpty.getProdPrptyValList()!=null && prpty.getProdPrptyValList().size()>0){
                    for(int j=0;j<prpty.getProdPrptyValList().size();j++){
                        if(StringUtils.isBlank(values)){
                            values = prpty.getProdPrptyValList().get(j).getPrptyValue();
                        }else{
                            values = values+";"+ prpty.getProdPrptyValList().get(j).getPrptyValue();
                        }
                    }
                }
                prptyType="";
                if(Constants.PRPTY_TYPE_SALE.equals(prpty.getPrptyType())){
                    prptyType = Constants.PRPTY_TYPE_SALE_NAME;
                }else if(Constants.PRPTY_TYPE_NATURE.equals(prpty.getPrptyType())){
                    prptyType = Constants.PRPTY_TYPE_NATURE_NAME;
                }else {
                    prptyType = prpty.getPrptyType();
                }
                prptyShowMap = new HashMap<String,String>();
                prptyShowMap.put("prptyName",prpty.getPrptyNameShow());
                prptyShowMap.put("prptyType",prptyType);
                prptyShowMap.put("values",values);
                prptyShowList.add(prptyShowMap);
            }
        }
        productViewDto.setPrptyShowList(prptyShowList);

        /**库存模板封装*********************/

        JSONArray labelArray = new JSONArray();
        JSONArray skuTableData = new JSONArray();

        this.buildSkuStoreShow(labelArray,skuTableData,pmProduct.getSkuInstList(),pmProduct.getProdStockSetList());

        productViewDto.setLabelArray(labelArray);
        productViewDto.setSkuTableData(skuTableData);

        if(pmProduct.getProdReleaseAreaList()!=null && pmProduct.getProdReleaseAreaList().size()>0){
            List<String> releaseAreaList = new ArrayList<>();
            String releaseAreaName;
            for(PmProdReleaseArea releaseArea : pmProduct.getProdReleaseAreaList()){
                releaseAreaName = releaseArea.getProvName();
                if(!StringUtils.isBlank(releaseArea.getCityName())){
                    releaseAreaName = releaseAreaName+"/"+releaseArea.getCityName();
                }
                if(!StringUtils.isBlank(releaseArea.getCountyName())){
                    releaseAreaName = releaseAreaName +"/"+releaseArea.getCountyName();
                }
                releaseAreaList.add(releaseAreaName);
            }
            productViewDto.setReleaseAreaList(releaseAreaList);
        }
        return productViewDto;
    }
    private void buildSkuStoreShow(JSONArray labelArray,JSONArray skuTableData,List<PmProdSkuInst> prodSkuInstList,List<PmProdStockSet> prodStockSetList){
        JSONObject labelObj = null;
        JSONObject dataObj = null;
        //封装表头
        if(prodSkuInstList!=null && prodSkuInstList.size()>0){
            PmProdSkuInst skuInst = prodSkuInstList.get(0);
            if(skuInst.getProdPricePlanPrptyRelList()!=null && skuInst.getProdPricePlanPrptyRelList().size()>0){
                PmProdPricePlanPrptyRel prptyRel;
                for(int i =0;i<skuInst.getProdPricePlanPrptyRelList().size();i++){
                    prptyRel = skuInst.getProdPricePlanPrptyRelList().get(i);

                    labelObj = new JSONObject();
                    labelObj.put("label", prptyRel.getPrptyNameShow());
                    labelObj.put("prop", "prpty_" + prptyRel.getPrptyCode());
                    labelArray.add(labelObj);
                }
                if (labelArray != null && labelArray.size() > 0) {
                    labelObj = new JSONObject();
                    labelObj.put("label", "价格");
                    labelObj.put("prop", "price");
                    labelArray.add(labelObj);
                    labelObj = new JSONObject();
                    labelObj.put("label", "服务时段");
                    labelObj.put("prop", "stockTime");
                    labelArray.add(labelObj);
                    labelObj = new JSONObject();
                    labelObj.put("label", "库存");
                    labelObj.put("prop", "stock");
                    labelArray.add(labelObj);
                }
            }
        }
        //封装数据
        if(prodStockSetList!=null && prodStockSetList.size()>0){
            for(PmProdStockSet pmProdStockSet : prodStockSetList){
                for(int i=0;i< prodSkuInstList.size();i++) {
                    PmProdSkuInst skuInst = prodSkuInstList.get(i);
                    dataObj= new JSONObject();
                    if (pmProdStockSet.getSkuInstId().longValue() == skuInst.getId().longValue()) {
                        dataObj.put("stockTime", pmProdStockSet.getStockTime());
                        dataObj.put("stock", pmProdStockSet.getTotalStock());

                        if(skuInst.getProdPricePlanPrptyRelList()!=null && skuInst.getProdPricePlanPrptyRelList().size()>0) {
                            PmProdPricePlanPrptyRel prptyRel;
                            for (int j = 0; j < skuInst.getProdPricePlanPrptyRelList().size(); j++) {
                                prptyRel=skuInst.getProdPricePlanPrptyRelList().get(j);
                                dataObj.put("prpty_"+prptyRel.getPrptyCode(),prptyRel.getPrptyValue());
                            }
                        }
                        dataObj.put("skuCode",skuInst.getCode());
                        dataObj.put("price",skuInst.getPrice());
                        skuTableData.add(dataObj);
                        break;
                    }
                }
            }
        }
    }
    private void converDataSkuStore(PmProductDto productDto){
//        if(productDto.getSkuInstList()!=null && productDto.getSkuInstList().size()>0){
//            /**1.构造表头数据***********/
//            JSONArray skuListLabel = new JSONArray();
//            JSONObject labelObj = null;
//            PmProdSkuInstDto skuDto = productDto.getSkuInstList().get(0);
//            if(skuDto.getSpecPricePlanPrptyRelList() !=null && skuDto.getSpecPricePlanPrptyRelList().size()>0) {
//                PmSpecPricePlanPrptyRel pricePlanPrptyRel = null;
//                for (int i = 0; i < skuDto.getSpecPricePlanPrptyRelList().size(); i++) {
//                    pricePlanPrptyRel = skuDto.getSpecPricePlanPrptyRelList().get(i);
//                    labelObj = new JSONObject();
//                    labelObj.put("label", pricePlanPrptyRel.getPrptyNameShow());
//                    labelObj.put("prop", "prpty_" + i);
//                    skuListLabel.add(labelObj);
//                }
//                labelObj = new JSONObject();
//                labelObj.put("label", "价格");
//                labelObj.put("prop", "price");
//                skuListLabel.add(labelObj);
//            }
//
//            /**2.构造表数据***********/
//            JSONArray skuTableData = new JSONArray();
//            JSONObject dataObj = null;
//            for(int j=0;j<prodSpecDto.getSpecSkuList().size();j++){
//
//                PmSpecSkuDto skuInfo = prodSpecDto.getSpecSkuList().get(j);
//                if(skuInfo.getSpecPricePlanPrptyRelList() ==null || skuInfo.getSpecPricePlanPrptyRelList().size()==0 ){
//                    continue;
//                }
//                String mainId ="";
//
//                dataObj = new JSONObject();
//                dataObj.put("price",skuInfo.getPrice());
//
//                PmSpecPricePlanPrptyRel pricePlanPrptyRel = null;
//                for (int i = 0; i < skuInfo.getSpecPricePlanPrptyRelList().size(); i++) {
//                    pricePlanPrptyRel =skuInfo.getSpecPricePlanPrptyRelList().get(i);
//                    dataObj.put("prpty_"+i,pricePlanPrptyRel.getPrptyValue());
//
//                    if(StringUtils.isBlank(mainId)){
//                        mainId =pricePlanPrptyRel.getPrptyCode()+","+pricePlanPrptyRel.getPrptyValCode();
//                    }else{
//                        mainId=mainId+";"+pricePlanPrptyRel.getPrptyCode()+","+pricePlanPrptyRel.getPrptyValCode();
//                    }
//                }
//                mainId=mainId+"|"+skuInfo.getPrice();
//                dataObj.put("mainId",mainId);
//                skuTableData.add(dataObj);
//            }
//            prodSpecDto.setSkuListLabel(skuListLabel);
//            prodSpecDto.setSkuTableData(skuTableData);
//        }
    }
//    private void converDataPic(PmProduct pmProduct){
//        Map<String,String> picMap  = new HashMap<String,String>();
//        String picUri;
//        if(pmProduct.getPicList()!=null && pmProduct.getPicList().size()>0){
//            for(PmProdPic pic: pmProduct.getPicList()){
//                picUri = picMap.get(pic.getPicType());
//                if(!StringUtils.isBlank(picUri)){
//                    picUri=picUri+";"+pic.getPicId();
//                }else{
//                    picUri=pic.getPicId();
//                }
//                picMap.put(pic.getPicType(),picUri);
//            }
//        }
//        /***业务代码*******************************************************************/
//        String picMain = picMap.get(Constants.PROD_SPEC_PIC_TYPE_MAIN);
//        if(!StringUtils.isBlank(picMain)){
//            pmProduct.setMainPicId(picMain);
//        }
//    }
    public int changeStatus(Long prodId,String prodCode,Integer status,String updateDesc){
        Date curDate = new Date();

        /*****1.先简单处理，有新的商品上架，作废原有正在上架商品。*/
        if(Constants.PROD_STATUS_CONFIG_VALID==status){

            PmProductExample example  = new PmProductExample();
            PmProductExample.Criteria criteria = example.createCriteria();
            criteria.andProdCodeEqualTo(prodCode);
            criteria.andStatusEqualTo(status);
            List<PmProduct>  productList=pmProductMapper.selectByExample(example);
            if(productList!=null && productList.size()>0){
                PmProduct pmProductMod = null;
                for(PmProduct pmProductDB :productList){
                    if(pmProductDB.getId().longValue()!=prodId.longValue()){
                        pmProductMod = new PmProduct();
                        pmProductMod.setId(pmProductDB.getId());
                        pmProductMod.setStatus(Constants.STATUS_INVALID);
                        // pmProductMod.setUpdateBy("xx");
                        pmProductMod.setUpdateTime(curDate);
                        pmProductMapper.updateByPrimaryKeySelective(pmProductMod);
                    }
                }
            }
        }
        /*****2.修改商品状态*********************************************************/
        PmProduct pmProductMod = new PmProduct();
        pmProductMod.setId(prodId);
        pmProductMod.setStatus(status);
        // pmProductMod.setUpdateBy("xx");
        pmProductMod.setUpdateTime(curDate);
//        pmProductMod.setProdDesc(product.getProdDesc());
        pmProductMod.setUpDesc(updateDesc);
        return  pmProductMapper.updateByPrimaryKeySelective(pmProductMod);
    }

    public  List<Map<String,Object>> listPageByMixture(int pageNum, int pageSize, String productName, Long channelId, Integer status){
        PageHelper.startPage(pageNum, pageSize);

        Map<String,Object> parmMap = new HashMap<String,Object>();
        if(!StringUtils.isBlank(productName)){
            parmMap.put("productName",productName);
        }
        if(channelId !=null ){
            parmMap.put("channelId",channelId);
        }
        if(status !=null){
            parmMap.put("status",status);
        }
        List<Map<String,Object>> dataList =pmProductMapper.listPageByMixture(parmMap);
        if(dataList !=null&& dataList.size()>0){
            Object statusObj = null;
            Object idObj =null;
            String statusDb = null;
            String idDb=null;

            Common queryCommon = new Common();
            queryCommon.setCommonType("prod_status");
            List<Common>  commonList = commonService.find(queryCommon);
            for(Map<String,Object> dbMap : dataList){
                statusObj =  dbMap.get("status");
                idObj= dbMap.get("id");
                dbMap.put("serverModeId","");
                dbMap.put("serverModeName","");
                dbMap.put("statusName","");
                if(statusObj!=null){
                    statusDb = statusObj.toString();
                    if(!StringUtils.isBlank(statusDb) && commonList!=null && commonList.size()>0){
                       for(Common common : commonList){
                           if(common.getCommonCode().equals(statusDb)){
                               dbMap.put("statusName",common.getCommonDesc().trim());
                           }
                       }
                    }
                }
                if(idObj!=null){
                    try{
                        idDb=idObj.toString();
                        if(!StringUtils.isBlank(idDb)){
                            List<PmProdServiceType>  serviceTypeList = this.getProdServiceType(Long.valueOf(idDb));
                            String serverModeId="";
                            String serverModeName="";
                            if(serviceTypeList!=null && serviceTypeList.size()>0){
                                for(PmProdServiceType serverType : serviceTypeList){
                                    if(StringUtils.isBlank(serverModeId)){
                                        serverModeId = serverType.getServiceType().toString();
                                        serverModeName = serverType.getServiceTypeName();
                                    }else{
                                        serverModeId = serverModeId +","+ serverType.getServiceType().toString();
                                        serverModeName = serverModeName +","+ serverType.getServiceTypeName();
                                    }
                                }
                            }
                            dbMap.put("serverModeId",serverModeId);
                            dbMap.put("serverModeName",serverModeName);
                        }
                    }catch (Exception e){
                        log.error(e.getMessage());
                    }
                }
            }
        }

        return dataList;
    }
    public JSONObject getProdStockSetListShow(String skuCodes,String releaseAreas,Long prodSpecId,Long productId,Long channelId)throws Exception{

        //校验时间段值是否为空
        List<String> stockTimeList = new ArrayList<>();
        PmProdSpecStockTempExample example = new PmProdSpecStockTempExample();
        PmProdSpecStockTempExample.Criteria criteria = example.createCriteria();
        criteria.andProdSpecIdEqualTo(prodSpecId);
        example.setOrderByClause(" temp_seq asc ");
        List<PmProdSpecStockTemp> tempList = pmProdSpecStockTempMapper.selectByExample(example);
        if(tempList!=null && tempList.size()>0){
            PmProdSpecStockTemp stockTemp = tempList.get(0);
            if(stockTemp!=null && !StringUtils.isBlank(stockTemp.getTempValue())){
                JSONArray jsonArray = JSONObject.parseArray(stockTemp.getTempValue());
                if( jsonArray !=null && jsonArray.size()>0 ){
                    for(int i =0 ;i<jsonArray.size();i++){
                        String time = jsonArray.getJSONObject(i).getString("time");
                        stockTimeList.add(time);
                        if(StringUtils.isBlank(time)){
                            throw new Exception("该服务的上门服务时间段为空，需要先进行设置");
                        }
                    }
                }
            }
        }else{
            throw new Exception("该服务的上门服务时间段为空，需要先进行设置");
        }

        List<List<String>> descartesList = this.generateDescartesList(skuCodes,releaseAreas,stockTimeList);
        log.debug("1.商品配置，生成笛卡尔积结果集："+descartesList.toString());
        JSONObject result = this.transDescartesList(descartesList,prodSpecId,productId,channelId);
        log.debug("2.商品配置，翻译后库存集合："+result.toString());

        return result;
    }
    private List<List<String>>  generateDescartesList(String skuCodes,String releaseAreas, List<String> stockTimeList){
        String[]  skuCodeArray = skuCodes.split(";");
        String[]  releaseAreaArray =  releaseAreas.split(";");

        List<String> skuCodeList = new ArrayList<>(skuCodeArray.length);
        Collections.addAll(skuCodeList,skuCodeArray);

        List<String> releaseAreaList = new ArrayList<>(releaseAreaArray.length);
        Collections.addAll(releaseAreaList,releaseAreaArray);


        List<List<String>> dimvalue = new ArrayList<>();
        dimvalue.add(skuCodeList);
        dimvalue.add(releaseAreaList);
        dimvalue.add(stockTimeList);
        List<List<String>> result = new ArrayList<List<String>>();

        this.descartes(dimvalue,result,0,new ArrayList<String>());

        return result;
    }
    private void descartes(List<List<String>> dimvalue, List<List<String>> result, int layer, List<String> curList) {
        if (layer < dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                descartes(dimvalue, result, layer + 1, curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    descartes(dimvalue, result, layer + 1, list);
                }
            }
        } else if (layer == dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                result.add(curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    result.add(list);
                }
            }
        }
    }
    private JSONObject transDescartesList( List<List<String>> descartesList,Long prodSpecId,Long productId,Long channelId){
        JSONObject result = new JSONObject();
        JSONArray stockSetLabel =new JSONArray();
        JSONArray stockSetData = new JSONArray();

        JSONObject stockSetInfo = null;
        //SKU信息
        PmProdSpec prodSpec = new PmProdSpec();
        PmSpecSku pmSpecSku = new PmSpecSku();
        pmSpecSku.setProdSpecId(prodSpecId);
        pmSpecSku.setStatus("0");
        prodSpec.setSpecSkuList(pmProdSpecSkuService.getSpecSkuList(pmSpecSku));
        PmProdSpecDto prodSpecDto = mapper.map(prodSpec,PmProdSpecDto.class);
        prodSpecService.converDataSku(prodSpecDto);
        JSONArray skuListLabel = prodSpecDto.getSkuListLabel();
        JSONArray skuTableData = prodSpecDto.getSkuTableData();

        log.debug("2.1 商品配置，获取商品规格SKU 表头信息："+skuListLabel.toString());
        JSONObject stockSetLabelInfo = null;
        for(int m=0;m<skuListLabel.size();m++){
            JSONObject skuLabel = skuListLabel.getJSONObject(m);
            stockSetLabelInfo = new JSONObject();
            Iterator iter = skuLabel.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                stockSetLabelInfo.put(entry.getKey().toString(),entry.getValue().toString());
            }
            stockSetLabel.add(stockSetLabelInfo);
        }
        stockSetLabelInfo = new JSONObject();
        stockSetLabelInfo.put("prop","releaseAreaName");
        stockSetLabelInfo.put("label","服务区域");
        stockSetLabel.add(stockSetLabelInfo);
        stockSetLabelInfo = new JSONObject();
        stockSetLabelInfo.put("prop","stockTime");
        stockSetLabelInfo.put("label","服务时段");
        stockSetLabel.add(stockSetLabelInfo);
        stockSetLabelInfo = new JSONObject();
        stockSetLabelInfo.put("prop","stock");
        stockSetLabelInfo.put("label","库存");
        stockSetLabel.add(stockSetLabelInfo);

        log.debug("2.2 商品配置，获取商品规格SKU 数据信息："+skuTableData.toString());

        //查询历史数据
        List<PmProdReleaseArea> releaseAreaDBList = null;
        Map<String,Long> releaseAreaDBMap = new HashMap<String,Long>();
        List<PmProdStockSet> stockSetList= null;
        if(productId!=null && channelId!=null){
            releaseAreaDBList = this.getProdReleaseArea(productId);
            if(releaseAreaDBList !=null &&  releaseAreaDBList.size()>0){
                String releaseAreaDBStr;
                for(PmProdReleaseArea releaseAreaDB :releaseAreaDBList) {
                    releaseAreaDBStr = releaseAreaDB.getProvCode();
                    if (!StringUtils.isBlank(releaseAreaDB.getCityCode())) {
                        releaseAreaDBStr = releaseAreaDBStr + "_" + releaseAreaDB.getCityCode();
                    }
                    if (!StringUtils.isBlank(releaseAreaDB.getCountyCode())) {
                        releaseAreaDBStr = releaseAreaDBStr + "_" + releaseAreaDB.getCountyCode();
                    }
                    releaseAreaDBMap.put(releaseAreaDBStr, releaseAreaDB.getId());
                }
            }
            stockSetList= this.getProdStockSet(productId);
        }


        Map<String,String> areaMap = new HashMap<String,String>();

        for(List<String> descartesInfo : descartesList){
            String skuCode=descartesInfo.get(0);
            String releaseArea =descartesInfo.get(1);
            String stockTime = descartesInfo.get(2);
            stockSetInfo = new JSONObject();

            stockSetInfo.put("stock",0);
            if(productId!=null && channelId!=null){
                PmProdStockSet prodStockSet= getStockSetOld(productId,channelId,skuCode,Constants.STOCK_TASK_TYPE_DAILY_DOOR,stockTime,releaseArea, releaseAreaDBMap,stockSetList);
                if(prodStockSet!=null){
                    stockSetInfo.put("stock",prodStockSet.getTotalStock());
                }
            }
            setDescartesSkuData(stockSetInfo,skuCode,skuTableData);
            setDescartesReleaseAreaData(stockSetInfo,releaseArea,areaMap);

            stockSetInfo.put("stockTime",stockTime);
            stockSetData.add(stockSetInfo);
        }
        result.put("stockSetLabel",stockSetLabel);
        result.put("stockSetData",stockSetData);

        log.debug("★★★★★★★★★★★★★★★★★★★★★★ 商品配置，库存初始化数据："+result.toString());

        return result;
    }
    private PmProdStockSet getStockSetOld(Long productId,Long channelId,String skuCode,int stockType,String stockTime,String releaseArea, Map<String,Long> releaseAreaDBMap,List<PmProdStockSet> stockSetList){
        if(!releaseAreaDBMap.isEmpty() && stockSetList!=null && stockSetList.size()>0){
            Long releaseAreaIdDB =releaseAreaDBMap.get(releaseArea);
            if(releaseAreaIdDB!=null){
                for(PmProdStockSet stockSetDB : stockSetList){
                    if(stockSetDB.getProdId().longValue()==productId.longValue()
                      && stockSetDB.getChannelId()== channelId.longValue()
                      && stockSetDB.getSkuCode().equals(skuCode)
                      && stockSetDB.getType().intValue()==stockType
                      && stockSetDB.getStockTime().equals(stockTime)
                      && stockSetDB.getReleaseAreaId()!=null && stockSetDB.getReleaseAreaId().longValue()==releaseAreaIdDB.longValue()){
                        return  stockSetDB;
                    }
                }
            }
        }
        return null;
    }
    private void setDescartesSkuData(JSONObject stockSetInfo, String skuCode,JSONArray skuTableData){
        JSONObject skuInfo;
        for(int i=0;i<skuTableData.size();i++){
            skuInfo = skuTableData.getJSONObject(i);
            if(skuCode.equals(skuInfo.getString("skuCode"))){
                Iterator iter = skuInfo.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    stockSetInfo.put(entry.getKey().toString(),entry.getValue().toString());
                }
            }
        }
    }
    private void setDescartesReleaseAreaData(JSONObject stockSetInfo,String releaseArea,Map<String,String> areaMap){
        stockSetInfo.put("releaseAreaId",releaseArea);
        stockSetInfo.put("releaseAreaName",releaseArea);
        if(!StringUtils.isBlank(releaseArea)){
            String releaseAreaName = areaMap.get(releaseArea);
            if(StringUtils.isBlank(releaseAreaName)){
                String[] releaseAreaInfoArray = releaseArea.split("_");
                releaseAreaName="";
                for(String areaCode :releaseAreaInfoArray){
                    if(!StringUtils.isBlank(areaCode)){
                        CnRegionInfo cnRegionInfoQry = new CnRegionInfo();
                        cnRegionInfoQry.setCriCode(areaCode);
                        CnRegionInfo cnRegionInfoDB= cnRegionInfoMapper.selectCnRegionInfoObjSingle(cnRegionInfoQry);
                        if(cnRegionInfoDB!=null ){
                            if(StringUtils.isBlank(releaseAreaName)){
                                releaseAreaName = cnRegionInfoDB.getCriName();
                            }else{
                                releaseAreaName = releaseAreaName+"/"+cnRegionInfoDB.getCriName();
                            }
                        }
                    }
                }
                areaMap.put(releaseArea,releaseAreaName);
            }
            stockSetInfo.put("releaseAreaName",releaseAreaName);
        }

    }
    public PmProdSpec getProdSpecByProdId(Long prodId){
        PmProduct product = pmProductMapper.selectByPrimaryKey(prodId);
        if(product==null || product.getId()==null){
            return new PmProdSpec();
        }
        PmProdSpec pmProdSpec = pmProdSpecMapper.selectByPrimaryKey(product.getProdSpecId());

        return pmProdSpec;
    }
}
